<template>
  <div class="demo-collapse">
    <div class="addBigTitle">
      <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加大题" @click="addBigSubject()"></vxe-button>
    </div>
    <!-- @change="handleChange" -->
    <el-scrollbar style="height: calc(100% - 34px)">
      <el-collapse v-model="activeNames">
        <el-collapse-item :name="item.seq" v-for="(item, index) in bigSubjects" :key="item.id">
          <template #title>
            <div class="collapseTitle">
              <span>{{ item.title }}：{{ item.description }}</span>
              <div>
                <el-tag size="small" style="margin-right: 10px"> {{ formatterType(item.subjectType) }}</el-tag>
                <el-button type="primary" @click.stop.prevent="addSmallSubject(item, index)" :icon="Plus" circle />
                <el-button type="warning" @click.stop.prevent="editBigSubject(item.id)" :icon="Edit" circle />
                <el-button type="danger" @click.stop.prevent="deleteBigSubject(item.id)" :icon="Delete" circle />
              </div>
            </div>
          </template>
          <div v-if="item.testSmallList && item.testSmallList.length > 0">
            <div class="collapseTitle" v-for="smallItem in item.testSmallList" :key="smallItem.id">
              <span style="margin-left: 17px; margin-bottom: 5px">{{ smallItem.seq + '. ' + smallItem.questionName }}</span>
              <div>
                <el-button style="margin-right: 30px" type="danger" @click.stop.prevent="deleteSmallSubject(smallItem.id, index, item.id)" :icon="Delete" circle size="small" />
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-scrollbar>

    <el-dialog v-model="addBigSubjectModel" title="添加大题目" width="600" height="400" draggable>
      <template #default>
        <el-form ref="testBigSubjectFormRef" :model="testBigSubjectForm" :rules="addBigSubjectRules" label-width="100px" class="form-input-m" v-loading="showBigLoading" inline-message>
          <el-scrollbar style="height: 100%">
            <el-form-item label="标题" prop="title">
              <el-input v-model="testBigSubjectForm.title" placeholder="标题" clearable></el-input>
            </el-form-item>
            <el-form-item label="题目类型" prop="subjectType">
              <el-select v-model="testBigSubjectForm.subjectType" placeholder="题目类型" style="width: 200px">
                <el-option v-for="item in subjectTypeOption" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item label="每题分值" prop="unitScore"> <el-input v-model="testBigSubjectForm.unitScore" placeholder="每题分值" clearable></el-input> </el-form-item>
            <el-form-item label="总分" prop="totalScore"> <el-input v-model="testBigSubjectForm.totalScore" placeholder="总分" clearable></el-input> </el-form-item>
            <el-form-item label="顺序" prop="seq">
              <el-input-number v-model="testBigSubjectForm.seq" :min="1" :max="1000" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="testBigSubjectForm.description" type="textarea" placeholder="描述" clearable style="margin-right: 10px"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remake">
              <el-input v-model="testBigSubjectForm.remake" type="textarea" placeholder="备注" clearable style="margin-right: 10px"></el-input>
            </el-form-item>
            <el-form-item class="form-footer">
              <template #default>
                <el-button type="primary" v-loading="saveBigLoading" @click="saveBigSubject()">保存</el-button>
                <el-button type="default" @click="addBigSubject()">重置</el-button>
              </template>
            </el-form-item>
          </el-scrollbar>
        </el-form>
      </template>
    </el-dialog>
    <el-dialog v-model="addSmallSubjectModel" title="添加小题目" width="600" height="415" draggable @close="resetSmallBuild">
      <template #default>
        <el-form ref="testSmallSubjectKnowledgeFormRef" :model="testSmallSubjectKnowledgeForm" :rules="addSmallSubjectRules" label-width="100px" class="form-input-m" v-loading="showSmallLoading" inline-message>
          <el-scrollbar style="height: 100%">
            <el-form-item label="知识库" prop="knowledgeIds">
              <el-tree-select v-model="testSmallSubjectKnowledgeForm.knowledgeIds" node-key="id" :data="knowledgeTreeOptions" :default-expanded-keys="[testSmallSubjectKnowledgeForm.knowledgeIds]" :default-checked-keys="[testSmallSubjectKnowledgeForm.knowledgeIds]" :render-after-expand="false" :props="defaultProps" show-checkbox multiple check-on-click-node style="width: 200px; margin-right: 10px" />
            </el-form-item>
            <el-form-item label="题目类型" prop="questionType">
              <el-select disabled v-model="testSmallSubjectKnowledgeForm.questionType" placeholder="题目类型" style="width: 200px">
                <el-option v-for="item in subjectTypeOption" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item label="题目分值" prop="score"> <el-input v-model="testSmallSubjectKnowledgeForm.score" placeholder="分数" clearable></el-input> </el-form-item>
            <el-form-item label="生成规则" prop="subjectRule"> <el-input v-model="testSmallSubjectKnowledgeForm.subjectRule" placeholder="生成规则" clearable></el-input> </el-form-item>
            <el-form-item label="题目数量" prop="count">
              <el-input-number v-model="testSmallSubjectKnowledgeForm.count" :min="1" :max="1000" />
            </el-form-item>
            <el-form-item class="form-footer">
              <template #default>
                <el-button type="primary" v-loading="saveSmallLoading" @click="buildSubject()">生成题目</el-button>
                <el-button type="default" @click="resetSmallBuild()">重置</el-button>
              </template>
            </el-form-item>
          </el-scrollbar>
        </el-form>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { Plus, Delete, Edit } from '@element-plus/icons-vue';

let { proxy }: any = getCurrentInstance();
defineExpose({ getBigSubjects });
const activeNames = ref([1]); //collapse绑定默认第一个展开
const addBigSubjectModel = ref(false); //添加大题目弹框展开状态
const addSmallSubjectModel = ref(false); //添加小题目弹框展开状态
let showBigLoading = ref(false); //大题目弹框加载状态
let showSmallLoading = ref(false); //小题目弹框加载状态
let saveBigLoading = ref(false); //大题目弹框表单保存状态
let saveSmallLoading = ref(false); //小题目弹框表单保存状态
//添加大题目弹框表单
const testBigSubjectForm = reactive({
  id: '',
  title: '',
  unitScore: '',
  totalScore: 0,
  subjectType: '',
  seq: 0,
  description: '',
  remake: '',
  paperId: '',
  testSmallList: []
});
//添加大题目弹框表单 校验规则
let addBigSubjectRules = {
  title: [{ required: true, message: '请输入标题' }],
  subjectType: [{ required: true, message: '请选择题型' }],
  unitScore: [{ required: true, message: '请输入分值' }],
  totalScore: [{ required: true, message: '请输入总分' }],
  seq: [{ required: true, message: '请输入序号' }],
  description: [{ required: true, message: '请输入描述' }]
};
//添加小题目弹框表单
const testSmallSubjectKnowledgeForm = reactive({
  paperId: '',
  bigSubjectId: '',
  knowledgeIds: [],
  questionType: '',
  score: '',
  subjectRule: '',
  count: 0
});
//添加小题目弹框表单 校验规则
let addSmallSubjectRules = {
  knowledgeIds: [{ required: true, message: '请选择知识库' }],
  questionType: [{ required: true, message: '请选择题目题型' }],
  count: [{ required: true, message: '请输入题目数量' }]
};

let bigSubjects = reactive([]); //大题项目
let currentBigIndex = ref(0);
let currenPaper = reactive({
  id: ''
});
const knowledgeTreeOptions = reactive([]); //小题目知识库选择下拉项
const defaultProps = {
  children: 'children',
  label: 'name'
};

let subjectTypeOption = reactive([]); //小题目题目类型字典选项数组

// 方法定义区 =============================================================
onMounted(() => {
  getBigSubjects(currenPaper);
  getDictItemsList();
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['question'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const qcRuleType = dictTreeTypeItems.data.find((item) => item.code === 'question');
  subjectTypeOption.push(...qcRuleType.detailDataList);
}

function getBigSubjects(currenPaperInfo: any) {
  Object.assign(currenPaper, currenPaperInfo);
  bigSubjects.length = 0;
  const url = '/wk/test/bigSubject/getTestBigSubjectList';
  proxy.$http
    .get(url, { params: { paperId: currenPaper.id } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        bigSubjects.push(...res.data);
        getKnowledgeTreeList();
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 获取知识树型数据
function getKnowledgeTreeList() {
  knowledgeTreeOptions.length = 0;
  const url = '/api/wk/wkKnowledge/getKnowledgeTree';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        knowledgeTreeOptions.push(...res.data);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
// 添加大题
function addBigSubject() {
  addBigSubjectModel.value = true;
  Object.keys(testBigSubjectForm).forEach((key) => {
    switch (typeof testBigSubjectForm[key]) {
      case 'string':
        testBigSubjectForm[key] = '';
        break;
      case 'number':
        testBigSubjectForm[key] = 0;
        break;
    }
    if (key === 'seq') {
      testBigSubjectForm[key] = bigSubjects.length + 1;
    }
    if (Array.isArray(testBigSubjectForm[key])) {
      testBigSubjectForm[key].length = 0;
    }
  });

  const el: any = proxy.$refs.testBigSubjectFormRef;
  if (el) {
    el.resetFields(); //重置该表单项，将其值重置为初始值，并移除校验结果
  }
}

// 编辑大题
function editBigSubject(bigSubjectId: any) {
  addBigSubjectModel.value = true;
  let editSubject = bigSubjects.find((item) => item.id === bigSubjectId);
  Object.assign(testBigSubjectForm, editSubject);
}

// 删除大题
function deleteBigSubject(bigSubjectId: any) {
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        const url = '/wk/test/bigSubject/deleteTestBigSubject';
        proxy.$http
          .post(url, { id: bigSubjectId })
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              getBigSubjects(currenPaper);
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

// 保存大题
function saveBigSubject() {
  let url = '';
  if (testBigSubjectForm.id == '' || testBigSubjectForm.id == null || testBigSubjectForm.id == undefined) {
    url = '/wk/test/bigSubject/addTestBigSubject';
  } else {
    url = '/wk/test/bigSubject/editTestBigSubject';
  }
  const el: any = proxy.$refs.testBigSubjectFormRef;
  saveBigLoading.value = true;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      saveBigLoading.value = false;
      return false;
    }
    testBigSubjectForm.paperId = currenPaper.id;
    proxy.$http
      .post(url, testBigSubjectForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        saveBigLoading.value = false;
        addBigSubjectModel.value = false;
        getBigSubjects(currenPaper);
      })
      .catch((err: any) => {
        saveBigLoading.value = false;
        VxeMessage(err, VxeNotifyType.error);
      });
  });
}

function addSmallSubject(bigSubject: any, index: any) {
  addSmallSubjectModel.value = true;
  testSmallSubjectKnowledgeForm.paperId = currenPaper.id;
  testSmallSubjectKnowledgeForm.bigSubjectId = bigSubject.id;
  testSmallSubjectKnowledgeForm.questionType = bigSubject.subjectType;
  currentBigIndex.value = index;
}

function formatterType(subjectType: any) {
  const item = subjectTypeOption.find((item) => item.code === subjectType);
  return item ? item.name : '';
}

// 根据知识库生成题目列表(添加小题目)
function buildSubject() {
  const url = '/wk/test/small/createSmallByKnowledgeIds';
  const el: any = proxy.$refs.testSmallSubjectKnowledgeFormRef;
  saveSmallLoading.value = true;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      saveSmallLoading.value = false;
      return false;
    }
    proxy.$http
      .post(url, testSmallSubjectKnowledgeForm)
      .then((res: any) => {
        if (res.status.code != 1) {
          VxeMessage('创建问题失败', VxeNotifyType.error);
        } else {
          VxeMessage('创建问题成功', VxeNotifyType.success);
          saveSmallLoading.value = false;
          addSmallSubjectModel.value = false;
          findSmallListByBigId(currentBigIndex.value, testSmallSubjectKnowledgeForm.bigSubjectId);
        }
      })
      .catch((err: any) => {
        saveSmallLoading.value = false;
        proxy.$alert(err, '提示');
      });
  });
}

// 重置小题目表单数据
function resetSmallBuild() {
  Object.keys(testSmallSubjectKnowledgeForm).forEach((key) => {
    switch (typeof testSmallSubjectKnowledgeForm[key]) {
      case 'string':
        testSmallSubjectKnowledgeForm[key] = '';
        break;
      case 'number':
        testSmallSubjectKnowledgeForm[key] = 0;
        break;
    }
    if (key === 'seq') {
      testSmallSubjectKnowledgeForm[key] = bigSubjects.length + 1;
    }
    if (Array.isArray(testSmallSubjectKnowledgeForm[key])) {
      testSmallSubjectKnowledgeForm[key].length = 0;
    }
  });
  const el: any = proxy.$refs.testSmallSubjectKnowledgeFormRef;
  if (el) {
    el.resetFields(); //重置该表单项，将其值重置为初始值，并移除校验结果
  }
}

// 根据大题id
function findSmallListByBigId(index: any, bigId: any) {
  bigSubjects[index].testSmallList.length = 0;
  const url = '/wk/test/small/getSmallSubjectList';
  proxy.$http
    .get(url, { params: { paperId: currenPaper.id, bigId: bigId } })
    .then((res: any) => {
      bigSubjects[index].testSmallList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 删除小题
function deleteSmallSubject(smallId: any, index: any, bigId: any) {
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        const url = '/wk/test/small/removeTestSmallSubject';
        proxy.$http
          .post(url, { id: smallId })
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              findSmallListByBigId(index, bigId);
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}
</script>

<style lang="scss" scoped>
.demo-collapse {
  height: 100%;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .addBigTitle {
    display: flex;
    align-items: center;
    justify-content: end;
  }
  .collapseTitle {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-right: 10px;
  }
}
</style>
